'use strict';

module.exports = (app) => {
  class ClassifyService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { Classify } = app.model.Tables.Web;
      const data = ctx.request.body;

      let isClassify = await Classify.findOne({
        where: {
          name: data.name,
          projectId: ctx.adminInfo.project_id,
        },
      });
      if (isClassify) {
        return '分类名已存在';
      }

      let res = await Classify.create({
        name: data.name,
        projectId: ctx.adminInfo.project_id,
      });
      console.log(res);
      return res;
    }

    async delete() {
      const { app, ctx } = this;
      const { Classify } = app.model.Tables.Web;
      const { id } = ctx.params;

      let res = await Classify.destroy({
        where: {
          id,
          projectId: ctx.adminInfo.project_id,
        },
      });
      if (res) {
        return '删除成功';
      } else {
        return 'id不存在,删除失败';
      }
    }

    async update() {
      const { app, ctx } = this;
      const { Classify } = app.model.Tables.Web;
      const data = ctx.request.body;
      let res = await Classify.update(
        {
          name: data.name,
        },
        {
          where: {
            id: data.id,
            projectId: ctx.adminInfo.project_id,
          },
        }
      );
      if (res[0]) {
        return '修改成功';
      } else {
        return 'id不存在,修改失败';
      }
    }

    async getAll() {
      const { app, ctx } = this;
      const { Classify } = app.model.Tables.Web;
      const data = ctx.query;

      let res = await Classify.findAndCountAll({
        where: {
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
        limit: Number(data.limit) || 10,
        offset: Number(data.offset) || 0,
      });
      return res;
    }

    async getById() {
      const { app, ctx } = this;
      const { Classify, Case } = app.model.Tables.Web;
      const data = ctx.query;
      let res = await Classify.findOne({
        include: [{ model: Case }],
        where: {
          id: data.id,
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
      });
      return res;
    }
  }
  return ClassifyService;
};
